<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.4.0">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">



<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@5.15.2/css/all.min.css">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/animate.css@3.1.1/animate.min.css">

<script class="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"littlefxc.github.io","root":"/","images":"/images","scheme":"Mist","version":"8.2.2","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12},"copycode":false,"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"fadeInDown","post_body":"fadeInDown","coll_header":"fadeInLeft","sidebar":"fadeInUp"}},"prism":false,"i18n":{"placeholder":"搜索...","empty":"没有找到任何搜索结果：${query}","hits_time":"找到 ${hits} 个搜索结果（用时 ${time} 毫秒）","hits":"找到 ${hits} 个搜索结果"},"path":"/search.xml","localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false}};
  </script>
<meta name="description" content="在 oauth2 的授权模式中有4种：  授权码模式 隐式授权模式 密码模式 客户端模式  但如果我们想要增加一个自定义的授权模式，又该怎么做呢？ 相关的源码是这样的： 123456789101112131415161718192021222324252627public class CompositeTokenGranter implements TokenGranter &amp;#123;	priv">
<meta property="og:type" content="article">
<meta property="og:title" content="Spring-Security-Oauth2如何增加自定义授权模式">
<meta property="og:url" content="http://littlefxc.github.io/2019/06/26/Spring-Security-Oauth2%E5%A6%82%E4%BD%95%E5%A2%9E%E5%8A%A0%E8%87%AA%E5%AE%9A%E4%B9%89%E6%8E%88%E6%9D%83%E6%A8%A1%E5%BC%8F/index.html">
<meta property="og:site_name" content="一年春又来">
<meta property="og:description" content="在 oauth2 的授权模式中有4种：  授权码模式 隐式授权模式 密码模式 客户端模式  但如果我们想要增加一个自定义的授权模式，又该怎么做呢？ 相关的源码是这样的： 123456789101112131415161718192021222324252627public class CompositeTokenGranter implements TokenGranter &amp;#123;	priv">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://img-blog.csdnimg.cn/20190618152045144.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L0xpdHRsZV9meGM=,size_16,color_FFFFFF,t_70">
<meta property="article:published_time" content="2019-06-26T03:17:29.000Z">
<meta property="article:modified_time" content="2021-03-25T13:15:49.013Z">
<meta property="article:author" content="一年春又来">
<meta property="article:tag" content="oauth2">
<meta property="article:tag" content="spring-boot">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://img-blog.csdnimg.cn/20190618152045144.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L0xpdHRsZV9meGM=,size_16,color_FFFFFF,t_70">


<link rel="canonical" href="http://littlefxc.github.io/2019/06/26/Spring-Security-Oauth2%E5%A6%82%E4%BD%95%E5%A2%9E%E5%8A%A0%E8%87%AA%E5%AE%9A%E4%B9%89%E6%8E%88%E6%9D%83%E6%A8%A1%E5%BC%8F/">


<script class="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>
<title>Spring-Security-Oauth2如何增加自定义授权模式 | 一年春又来</title>
  




  <noscript>
  <style>
  body { margin-top: 2rem; }

  .use-motion .menu-item,
  .use-motion .sidebar,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header {
    visibility: visible;
  }

  .use-motion .header,
  .use-motion .site-brand-container .toggle,
  .use-motion .footer { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle,
  .use-motion .custom-logo-image {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line {
    transform: scaleX(1);
  }

  .search-pop-overlay, .sidebar-nav { display: none; }
  .sidebar-panel { display: block; }
  </style>
</noscript>

<link rel="alternate" href="/atom.xml" title="一年春又来" type="application/atom+xml">
</head>

<body itemscope itemtype="http://schema.org/WebPage" class="use-motion">
  <div class="headband"></div>

  <main class="main">
    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏" role="button">
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <i class="logo-line"></i>
      <h1 class="site-title">一年春又来</h1>
      <i class="logo-line"></i>
    </a>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>



<nav class="site-nav">
  <ul class="main-menu menu">
        <li class="menu-item menu-item-home"><a href="/" rel="section"><i class="home                          //首页 fa-fw"></i>首页</a></li>
        <li class="menu-item menu-item-archives"><a href="/archives/" rel="section"><i class="archive          //归档 fa-fw"></i>归档</a></li>
        <li class="menu-item menu-item-categories"><a href="/categories/" rel="section"><i class="th           //分类 fa-fw"></i>分类</a></li>
        <li class="menu-item menu-item-tags"><a href="/tags/" rel="section"><i class="tags                     //标签 fa-fw"></i>标签</a></li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup"><div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off" maxlength="80"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close" role="button">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div class="search-result-container no-result">
  <div class="search-result-icon">
    <i class="fa fa-spinner fa-pulse fa-5x"></i>
  </div>
</div>

    </div>
  </div>

</div>
        
  
  <div class="toggle sidebar-toggle" role="button">
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
  </div>

  <aside class="sidebar">

    <div class="sidebar-inner sidebar-nav-active sidebar-toc-active">
      <ul class="sidebar-nav">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <div class="sidebar-panel-container">
        <!--noindex-->
        <div class="post-toc-wrap sidebar-panel">
            <div class="post-toc animated"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E8%87%AA%E5%AE%9A%E4%B9%89%E6%8E%88%E6%9D%83%E6%A8%A1%E5%BC%8F%EF%BC%9ASmsCodeTokenGranter"><span class="nav-text">自定义授权模式：SmsCodeTokenGranter</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E6%8E%88%E6%9D%83%E6%A8%A1%E5%BC%8F%E9%85%8D%E7%BD%AE%E7%B1%BB%EF%BC%9ATokenGranterConfig"><span class="nav-text">授权模式配置类：TokenGranterConfig</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E6%8E%88%E6%9D%83%E8%AE%A4%E8%AF%81%E6%9C%8D%E5%8A%A1%E7%AB%AF%E7%82%B9%E9%85%8D%E7%BD%AE"><span class="nav-text">授权认证服务端点配置</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E6%BC%94%E7%A4%BA%E6%95%88%E6%9E%9C"><span class="nav-text">演示效果</span></a></li></ol></div>
        </div>
        <!--/noindex-->

        <div class="site-overview-wrap sidebar-panel">
          <div class="site-author site-overview-item animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <p class="site-author-name" itemprop="name">一年春又来</p>
  <div class="site-description" itemprop="description"></div>
</div>
<div class="site-state-wrap site-overview-item animated">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">234</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/categories/">
          
        <span class="site-state-item-count">38</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/tags/">
          
        <span class="site-state-item-count">125</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>



        </div>
      </div>
    </div>
  </aside>
  <div class="sidebar-dimmer"></div>


    </header>

    
  <div class="back-to-top" role="button">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>

<noscript>
  <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
</noscript>


    <div class="main-inner post posts-expand">


  


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://littlefxc.github.io/2019/06/26/Spring-Security-Oauth2%E5%A6%82%E4%BD%95%E5%A2%9E%E5%8A%A0%E8%87%AA%E5%AE%9A%E4%B9%89%E6%8E%88%E6%9D%83%E6%A8%A1%E5%BC%8F/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.gif">
      <meta itemprop="name" content="一年春又来">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="一年春又来">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          Spring-Security-Oauth2如何增加自定义授权模式
        </h1>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">发表于</span>

      <time title="创建时间：2019-06-26 11:17:29" itemprop="dateCreated datePublished" datetime="2019-06-26T11:17:29+08:00">2019-06-26</time>
    </span>
      <span class="post-meta-item">
        <span class="post-meta-item-icon">
          <i class="far fa-calendar-check"></i>
        </span>
        <span class="post-meta-item-text">更新于</span>
        <time title="修改时间：2021-03-25 21:15:49" itemprop="dateModified" datetime="2021-03-25T21:15:49+08:00">2021-03-25</time>
      </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">分类于</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/categories/oauth2/" itemprop="url" rel="index"><span itemprop="name">oauth2</span></a>
        </span>
    </span>

  
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">
        <p>在 oauth2 的授权模式中有4种：</p>
<ul>
<li>授权码模式</li>
<li>隐式授权模式</li>
<li>密码模式</li>
<li>客户端模式</li>
</ul>
<p>但如果我们想要增加一个自定义的授权模式，又该怎么做呢？</p>
<p>相关的源码是这样的：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">CompositeTokenGranter</span> <span class="keyword">implements</span> <span class="title">TokenGranter</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">	<span class="keyword">private</span> <span class="keyword">final</span> List&lt;TokenGranter&gt; tokenGranters;</span><br><span class="line"></span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="title">CompositeTokenGranter</span><span class="params">(List&lt;TokenGranter&gt; tokenGranters)</span> </span>&#123;</span><br><span class="line">		<span class="keyword">this</span>.tokenGranters = <span class="keyword">new</span> ArrayList&lt;TokenGranter&gt;(tokenGranters);</span><br><span class="line">	&#125;</span><br><span class="line">	</span><br><span class="line">	<span class="comment">//四种授权模式+刷新令牌的模式根据grant_type判断</span></span><br><span class="line">	<span class="function"><span class="keyword">public</span> OAuth2AccessToken <span class="title">grant</span><span class="params">(String grantType, TokenRequest tokenRequest)</span> </span>&#123;</span><br><span class="line">		<span class="keyword">for</span> (TokenGranter granter : tokenGranters) &#123;</span><br><span class="line">			OAuth2AccessToken grant = granter.grant(grantType, tokenRequest);</span><br><span class="line">			<span class="keyword">if</span> (grant!=<span class="keyword">null</span>) &#123;</span><br><span class="line">				<span class="keyword">return</span> grant;</span><br><span class="line">			&#125;</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">	&#125;</span><br><span class="line">	</span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">addTokenGranter</span><span class="params">(TokenGranter tokenGranter)</span> </span>&#123;</span><br><span class="line">		<span class="keyword">if</span> (tokenGranter == <span class="keyword">null</span>) &#123;</span><br><span class="line">			<span class="keyword">throw</span> <span class="keyword">new</span> IllegalArgumentException(<span class="string">&quot;Token granter is null&quot;</span>);</span><br><span class="line">		&#125;</span><br><span class="line">		tokenGranters.add(tokenGranter);</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>oauth2 端点配置类部分源码：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">final</span> <span class="class"><span class="keyword">class</span> <span class="title">AuthorizationServerEndpointsConfigurer</span> </span>&#123;</span><br><span class="line">    </span><br><span class="line">    <span class="comment">// 省略部分代码</span></span><br><span class="line">    </span><br><span class="line">    <span class="keyword">private</span> TokenGranter tokenGranter;</span><br><span class="line">    </span><br><span class="line">    <span class="function"><span class="keyword">public</span> AuthorizationServerEndpointsConfigurer <span class="title">tokenGranter</span><span class="params">(TokenGranter tokenGranter)</span> </span>&#123;</span><br><span class="line">    	<span class="keyword">this</span>.tokenGranter = tokenGranter;</span><br><span class="line">    	<span class="keyword">return</span> <span class="keyword">this</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="comment">// 默认的四种授权模式+刷新令牌的模式的配置</span></span><br><span class="line">    <span class="function"><span class="keyword">private</span> TokenGranter <span class="title">tokenGranter</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    	<span class="keyword">if</span> (tokenGranter == <span class="keyword">null</span>) &#123;</span><br><span class="line">    		tokenGranter = <span class="keyword">new</span> TokenGranter() &#123;</span><br><span class="line">    			<span class="keyword">private</span> CompositeTokenGranter delegate;</span><br><span class="line">    </span><br><span class="line">    			<span class="meta">@Override</span></span><br><span class="line">    			<span class="function"><span class="keyword">public</span> OAuth2AccessToken <span class="title">grant</span><span class="params">(String grantType, TokenRequest tokenRequest)</span> </span>&#123;</span><br><span class="line">    				<span class="keyword">if</span> (delegate == <span class="keyword">null</span>) &#123;</span><br><span class="line">    					delegate = <span class="keyword">new</span> CompositeTokenGranter(getDefaultTokenGranters());</span><br><span class="line">    				&#125;</span><br><span class="line">    				<span class="keyword">return</span> delegate.grant(grantType, tokenRequest);</span><br><span class="line">    			&#125;</span><br><span class="line">    		&#125;;</span><br><span class="line">    	&#125;</span><br><span class="line">    	<span class="keyword">return</span> tokenGranter;</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="comment">// 默认的四种授权模式+刷新令牌的模式的配置</span></span><br><span class="line">    <span class="function"><span class="keyword">private</span> List&lt;TokenGranter&gt; <span class="title">getDefaultTokenGranters</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    	ClientDetailsService clientDetails = clientDetailsService();</span><br><span class="line">    	AuthorizationServerTokenServices tokenServices = tokenServices();</span><br><span class="line">    	AuthorizationCodeServices authorizationCodeServices = authorizationCodeServices();</span><br><span class="line">    	OAuth2RequestFactory requestFactory = requestFactory();</span><br><span class="line">    	</span><br><span class="line">    	List&lt;TokenGranter&gt; tokenGranters = <span class="keyword">new</span> ArrayList&lt;TokenGranter&gt;();</span><br><span class="line">    	<span class="comment">// 添加授权码模式</span></span><br><span class="line">    	tokenGranters.add(<span class="keyword">new</span> AuthorizationCodeTokenGranter(tokenServices, authorizationCodeServices, clientDetails,</span><br><span class="line">    			requestFactory));</span><br><span class="line">    	<span class="comment">// 添加刷新令牌的模式</span></span><br><span class="line">    	tokenGranters.add(<span class="keyword">new</span> RefreshTokenGranter(tokenServices, clientDetails, requestFactory));</span><br><span class="line">    	<span class="comment">// 添加隐式授权模式</span></span><br><span class="line">    	ImplicitTokenGranter implicit = <span class="keyword">new</span> ImplicitTokenGranter(tokenServices, clientDetails, requestFactory);</span><br><span class="line">    	tokenGranters.add(implicit);</span><br><span class="line">    	<span class="comment">// 添加客户端模式</span></span><br><span class="line">    	tokenGranters.add(<span class="keyword">new</span> ClientCredentialsTokenGranter(tokenServices, clientDetails, requestFactory));</span><br><span class="line">    	<span class="keyword">if</span> (authenticationManager != <span class="keyword">null</span>) &#123;</span><br><span class="line">    	    <span class="comment">// 添加密码模式</span></span><br><span class="line">    		tokenGranters.add(<span class="keyword">new</span> ResourceOwnerPasswordTokenGranter(authenticationManager, tokenServices,</span><br><span class="line">    				clientDetails, requestFactory));</span><br><span class="line">    	&#125;</span><br><span class="line">    	</span><br><span class="line">    	<span class="comment">// 可以复制相关代码，然后这里添加自定义的授权模式</span></span><br><span class="line">    	</span><br><span class="line">    	<span class="keyword">return</span> tokenGranters;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>看到这里就可以发现 spring 已经把默认的四种授权模式+刷新令牌的模式的配置在代码中写死了!</p>
<p>那又如何添加自定义的授权模式呢？</p>
<p>我的思路是这样的：</p>
<p>直接把这部分的代码复制，在其中添加自定义的授权模式。</p>
<p>我直接把密码模式复制，将其中的 <code>GRANT_TYPE</code> 的值改为 <code>sms_code</code>,然后使用 <code>/oauth/token?grant_type=sms_code&amp;scope=read&amp;username=user&amp;password=123456</code> 来验证结果。</p>
<h2 id="自定义授权模式：SmsCodeTokenGranter"><a href="#自定义授权模式：SmsCodeTokenGranter" class="headerlink" title="自定义授权模式：SmsCodeTokenGranter"></a>自定义授权模式：SmsCodeTokenGranter</h2><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@author</span> fengxuechao</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@version</span> 0.1</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@date</span> 2019/5/17</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">SmsCodeTokenGranter</span> <span class="keyword">extends</span> <span class="title">AbstractTokenGranter</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 仅仅复制了 ResourceOwnerPasswordTokenGranter，只是改变了 GRANT_TYPE 的值，来验证自定义授权模式的可行性</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> String GRANT_TYPE = <span class="string">&quot;sms_code&quot;</span>;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> AuthenticationManager authenticationManager;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">SmsCodeTokenGranter</span><span class="params">(</span></span></span><br><span class="line"><span class="function"><span class="params">            AuthenticationManager authenticationManager,</span></span></span><br><span class="line"><span class="function"><span class="params">            AuthorizationServerTokenServices tokenServices,</span></span></span><br><span class="line"><span class="function"><span class="params">            ClientDetailsService clientDetailsService,</span></span></span><br><span class="line"><span class="function"><span class="params">            OAuth2RequestFactory requestFactory)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>(authenticationManager, tokenServices, clientDetailsService, requestFactory, GRANT_TYPE);</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">protected</span> <span class="title">SmsCodeTokenGranter</span><span class="params">(</span></span></span><br><span class="line"><span class="function"><span class="params">            AuthenticationManager authenticationManager,</span></span></span><br><span class="line"><span class="function"><span class="params">            AuthorizationServerTokenServices tokenServices,</span></span></span><br><span class="line"><span class="function"><span class="params">            ClientDetailsService clientDetailsService,</span></span></span><br><span class="line"><span class="function"><span class="params">            OAuth2RequestFactory requestFactory,</span></span></span><br><span class="line"><span class="function"><span class="params">            String grantType)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">super</span>(tokenServices, clientDetailsService, requestFactory, grantType);</span><br><span class="line">        <span class="keyword">this</span>.authenticationManager = authenticationManager;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">protected</span> OAuth2Authentication <span class="title">getOAuth2Authentication</span><span class="params">(ClientDetails client, TokenRequest tokenRequest)</span> </span>&#123;</span><br><span class="line">        Map&lt;String, String&gt; parameters = <span class="keyword">new</span> LinkedHashMap&lt;String, String&gt;(tokenRequest.getRequestParameters());</span><br><span class="line">        String username = parameters.get(<span class="string">&quot;username&quot;</span>);</span><br><span class="line">        String password = parameters.get(<span class="string">&quot;password&quot;</span>);</span><br><span class="line">        <span class="comment">// Protect from downstream leaks of password</span></span><br><span class="line">        parameters.remove(<span class="string">&quot;password&quot;</span>);</span><br><span class="line"></span><br><span class="line">        Authentication userAuth = <span class="keyword">new</span> UsernamePasswordAuthenticationToken(username, password);</span><br><span class="line">        ((AbstractAuthenticationToken) userAuth).setDetails(parameters);</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            userAuth = authenticationManager.authenticate(userAuth);</span><br><span class="line">        &#125; <span class="keyword">catch</span> (AccountStatusException ase) &#123;</span><br><span class="line">            <span class="comment">//covers expired, locked, disabled cases (mentioned in section 5.2, draft 31)</span></span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> InvalidGrantException(ase.getMessage());</span><br><span class="line">        &#125; <span class="keyword">catch</span> (BadCredentialsException e) &#123;</span><br><span class="line">            <span class="comment">// If the username/password are wrong the spec says we should send 400/invalid grant</span></span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> InvalidGrantException(e.getMessage());</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">if</span> (userAuth == <span class="keyword">null</span> || !userAuth.isAuthenticated()) &#123;</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> InvalidGrantException(<span class="string">&quot;Could not authenticate user: &quot;</span> + username);</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        OAuth2Request storedOAuth2Request = getRequestFactory().createOAuth2Request(client, tokenRequest);</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> OAuth2Authentication(storedOAuth2Request, userAuth);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="授权模式配置类：TokenGranterConfig"><a href="#授权模式配置类：TokenGranterConfig" class="headerlink" title="授权模式配置类：TokenGranterConfig"></a>授权模式配置类：TokenGranterConfig</h2><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br><span class="line">140</span><br><span class="line">141</span><br><span class="line">142</span><br><span class="line">143</span><br><span class="line">144</span><br><span class="line">145</span><br><span class="line">146</span><br><span class="line">147</span><br><span class="line">148</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@author</span> fengxuechao</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@version</span> 0.1</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@date</span> 2019/5/17</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="meta">@Configuration</span></span><br><span class="line"><span class="meta">@Profile(&quot;inMemory&quot;)</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">TokenGranterConfig</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    <span class="keyword">private</span> ClientDetailsService clientDetailsService;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    <span class="keyword">private</span> UserDetailsService userDetailsService;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    <span class="keyword">private</span> AuthenticationManager authenticationManager;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    <span class="keyword">private</span> TokenStore tokenStore;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    TokenEnhancer tokenEnhancer;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> AuthorizationCodeServices authorizationCodeServices;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">boolean</span> reuseRefreshToken = <span class="keyword">true</span>;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> AuthorizationServerTokenServices tokenServices;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> TokenGranter tokenGranter;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 授权模式</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@Bean</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> TokenGranter <span class="title">tokenGranter</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (tokenGranter == <span class="keyword">null</span>) &#123;</span><br><span class="line">            tokenGranter = <span class="keyword">new</span> TokenGranter() &#123;</span><br><span class="line">                <span class="keyword">private</span> CompositeTokenGranter delegate;</span><br><span class="line"></span><br><span class="line">                <span class="meta">@Override</span></span><br><span class="line">                <span class="function"><span class="keyword">public</span> OAuth2AccessToken <span class="title">grant</span><span class="params">(String grantType, TokenRequest tokenRequest)</span> </span>&#123;</span><br><span class="line">                    <span class="keyword">if</span> (delegate == <span class="keyword">null</span>) &#123;</span><br><span class="line">                        delegate = <span class="keyword">new</span> CompositeTokenGranter(getDefaultTokenGranters());</span><br><span class="line">                    &#125;</span><br><span class="line">                    <span class="keyword">return</span> delegate.grant(grantType, tokenRequest);</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> tokenGranter;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 程序支持的授权类型</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">private</span> List&lt;TokenGranter&gt; <span class="title">getDefaultTokenGranters</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        AuthorizationServerTokenServices tokenServices = tokenServices();</span><br><span class="line">        AuthorizationCodeServices authorizationCodeServices = authorizationCodeServices();</span><br><span class="line">        OAuth2RequestFactory requestFactory = requestFactory();</span><br><span class="line"></span><br><span class="line">        List&lt;TokenGranter&gt; tokenGranters = <span class="keyword">new</span> ArrayList&lt;TokenGranter&gt;();</span><br><span class="line">        <span class="comment">// 添加授权码模式</span></span><br><span class="line">        tokenGranters.add(<span class="keyword">new</span> AuthorizationCodeTokenGranter(tokenServices, authorizationCodeServices, clientDetailsService, requestFactory));</span><br><span class="line">        <span class="comment">// 添加刷新令牌的模式</span></span><br><span class="line">        tokenGranters.add(<span class="keyword">new</span> RefreshTokenGranter(tokenServices, clientDetailsService, requestFactory));</span><br><span class="line">        <span class="comment">// 添加隐士授权模式</span></span><br><span class="line">        tokenGranters.add(<span class="keyword">new</span> ImplicitTokenGranter(tokenServices, clientDetailsService, requestFactory));</span><br><span class="line">        <span class="comment">// 添加客户端模式</span></span><br><span class="line">        tokenGranters.add(<span class="keyword">new</span> ClientCredentialsTokenGranter(tokenServices, clientDetailsService, requestFactory));</span><br><span class="line">        <span class="keyword">if</span> (authenticationManager != <span class="keyword">null</span>) &#123;</span><br><span class="line">            <span class="comment">// 添加密码模式</span></span><br><span class="line">            tokenGranters.add(<span class="keyword">new</span> ResourceOwnerPasswordTokenGranter(authenticationManager, tokenServices, clientDetailsService, requestFactory));</span><br><span class="line">            <span class="comment">// 添加自定义授权模式（实际是密码模式的复制）</span></span><br><span class="line">            tokenGranters.add(<span class="keyword">new</span> SmsCodeTokenGranter(authenticationManager, tokenServices, clientDetailsService, requestFactory));</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> tokenGranters;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * TokenServices</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">private</span> AuthorizationServerTokenServices <span class="title">tokenServices</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (tokenServices != <span class="keyword">null</span>) &#123;</span><br><span class="line">            <span class="keyword">return</span> tokenServices;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">this</span>.tokenServices = createDefaultTokenServices();</span><br><span class="line">        <span class="keyword">return</span> tokenServices;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 授权码API</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">private</span> AuthorizationCodeServices <span class="title">authorizationCodeServices</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (authorizationCodeServices == <span class="keyword">null</span>) &#123;</span><br><span class="line">            authorizationCodeServices = <span class="keyword">new</span> InMemoryAuthorizationCodeServices();</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> authorizationCodeServices;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * OAuth2RequestFactory的默认实现，它初始化参数映射中的字段，</span></span><br><span class="line"><span class="comment">     * 验证授权类型(grant_type)和范围(scope)，并使用客户端的默认值填充范围(scope)（如果缺少这些值）。</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">private</span> OAuth2RequestFactory <span class="title">requestFactory</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> DefaultOAuth2RequestFactory(clientDetailsService);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 默认 TokenService</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">private</span> DefaultTokenServices <span class="title">createDefaultTokenServices</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        DefaultTokenServices tokenServices = <span class="keyword">new</span> DefaultTokenServices();</span><br><span class="line">        tokenServices.setTokenStore(tokenStore);</span><br><span class="line">        tokenServices.setSupportRefreshToken(<span class="keyword">true</span>);</span><br><span class="line">        tokenServices.setReuseRefreshToken(reuseRefreshToken);</span><br><span class="line">        tokenServices.setClientDetailsService(clientDetailsService);</span><br><span class="line">        tokenServices.setTokenEnhancer(tokenEnhancer);</span><br><span class="line">        addUserDetailsService(tokenServices, <span class="keyword">this</span>.userDetailsService);</span><br><span class="line">        <span class="keyword">return</span> tokenServices;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 添加预身份验证</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> tokenServices</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> userDetailsService</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">addUserDetailsService</span><span class="params">(DefaultTokenServices tokenServices, UserDetailsService userDetailsService)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (userDetailsService != <span class="keyword">null</span>) &#123;</span><br><span class="line">            PreAuthenticatedAuthenticationProvider provider = <span class="keyword">new</span> PreAuthenticatedAuthenticationProvider();</span><br><span class="line">            provider.setPreAuthenticatedUserDetailsService(<span class="keyword">new</span> UserDetailsByNameServiceWrapper&lt;PreAuthenticatedAuthenticationToken&gt;(userDetailsService));</span><br><span class="line">            tokenServices.setAuthenticationManager(<span class="keyword">new</span> ProviderManager(Arrays.&lt;AuthenticationProvider&gt;asList(provider)));</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="授权认证服务端点配置"><a href="#授权认证服务端点配置" class="headerlink" title="授权认证服务端点配置"></a>授权认证服务端点配置</h2><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.fengxuechao.examples.auth.config.inmemory;</span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@author</span> fengxuechao</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@version</span> 0.1</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@date</span> 2019/5/8</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="meta">@Slf4j</span></span><br><span class="line"><span class="meta">@EnableAuthorizationServer</span></span><br><span class="line"><span class="meta">@Configuration</span></span><br><span class="line"><span class="meta">@Profile(&quot;inMemory&quot;)</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">AuthorizationServerConfigInMemory</span> <span class="keyword">extends</span> <span class="title">AuthorizationServerConfigurerAdapter</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 省略部分代码</span></span><br><span class="line">    </span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    <span class="keyword">private</span> TokenGranter tokenGranter;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 认证服务器节点配置</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> endpoints</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@throws</span> Exception</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">configure</span><span class="params">(AuthorizationServerEndpointsConfigurer endpoints)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">        endpoints</span><br><span class="line">                .tokenGranter(tokenGranter) <span class="comment">// 四种授权模式+刷新令牌的模式+自定义授权模式</span></span><br><span class="line">                .tokenStore(tokenStore)</span><br><span class="line">                .approvalStore(approvalStore)</span><br><span class="line">                .userDetailsService(userDetailsService)</span><br><span class="line">                .authenticationManager(authenticationManager)</span><br><span class="line">                .setClientDetailsService(clientDetailsService);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="演示效果"><a href="#演示效果" class="headerlink" title="演示效果"></a>演示效果</h2><p><img src="https://img-blog.csdnimg.cn/20190618152045144.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L0xpdHRsZV9meGM=,size_16,color_FFFFFF,t_70" alt="在这里插入图片描述"></p>
<figure class="highlight"><figcaption><span>request</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line">POST http://localhost:8080/oauth/token?grant_type=sms_code&amp;scope=read&amp;username=user&amp;password=123456</span><br><span class="line"></span><br><span class="line"><span class="meta">HTTP/1.1</span> <span class="number">200</span> </span><br><span class="line"><span class="attribute">X-Application-Context</span><span class="punctuation">: </span>application:inMemory</span><br><span class="line"><span class="attribute">Cache-Control</span><span class="punctuation">: </span>no-store</span><br><span class="line"><span class="attribute">Pragma</span><span class="punctuation">: </span>no-cache</span><br><span class="line"><span class="attribute">X-Content-Type-Options</span><span class="punctuation">: </span>nosniff</span><br><span class="line"><span class="attribute">X-XSS-Protection</span><span class="punctuation">: </span>1; mode=block</span><br><span class="line"><span class="attribute">X-Frame-Options</span><span class="punctuation">: </span>DENY</span><br><span class="line"><span class="attribute">Content-Type</span><span class="punctuation">: </span>application/json;charset=UTF-8</span><br><span class="line"><span class="attribute">Transfer-Encoding</span><span class="punctuation">: </span>chunked</span><br><span class="line"><span class="attribute">Date</span><span class="punctuation">: </span>Tue, 18 Jun 2019 07:13:12 GMT</span><br><span class="line"></span><br><span class="line">&#123;</span><br><span class="line">  &quot;access_token&quot;: &quot;19f2e44a-6c9a-45c4-be7e-0aada6a0a9e6&quot;,</span><br><span class="line">  &quot;token_type&quot;: &quot;bearer&quot;,</span><br><span class="line">  &quot;refresh_token&quot;: &quot;f59336a8-03c4-4c85-bc31-16c6d80f1381&quot;,</span><br><span class="line">  &quot;expires_in&quot;: 359,</span><br><span class="line">  &quot;scope&quot;: &quot;read&quot;,</span><br><span class="line">  &quot;organization&quot;: &quot;userWqTI&quot;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">Response code: 200; Time: 335ms; Content length: 190 bytes</span><br></pre></td></tr></table></figure>

    </div>

    
    
    

    <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/oauth2/" rel="tag"># oauth2</a>
              <a href="/tags/spring-boot/" rel="tag"># spring-boot</a>
          </div>

        

          <div class="post-nav">
            <div class="post-nav-item">
                <a href="/2019/06/26/Spring-Security-Oauth2%E6%B7%BB%E5%8A%A0%E8%87%AA%E5%AE%9A%E4%B9%89%E8%BF%87%E6%BB%A4%E5%99%A8%E5%92%8Coauth2%E8%AE%A4%E8%AF%81%E5%90%8EAPI%E6%9D%83%E9%99%90%E6%8E%A7%E5%88%B6/" rel="prev" title="Spring-Security-Oauth2添加自定义过滤器和oauth2认证后API权限控制">
                  <i class="fa fa-chevron-left"></i> Spring-Security-Oauth2添加自定义过滤器和oauth2认证后API权限控制
                </a>
            </div>
            <div class="post-nav-item">
                <a href="/2019/06/26/logback-Kafka-logstash%E9%9B%86%E6%88%90/" rel="next" title="logback+Kafka+logstash集成">
                  logback+Kafka+logstash集成 <i class="fa fa-chevron-right"></i>
                </a>
            </div>
          </div>
    </footer>
  </article>
</div>







<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      const activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      const commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>
</div>
  </main>

  <footer class="footer">
    <div class="footer-inner">


<div class="copyright">
  &copy; 
  <span itemprop="copyrightYear">2022</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">一年春又来</span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.js.org/mist/" class="theme-link" rel="noopener" target="_blank">NexT.Mist</a> 强力驱动
  </div>

    </div>
  </footer>

  
  <script src="https://cdn.jsdelivr.net/npm/animejs@3.2.1/lib/anime.min.js"></script>
<script src="/js/utils.js"></script><script src="/js/motion.js"></script><script src="/js/schemes/muse.js"></script><script src="/js/next-boot.js"></script>

  
<script src="/js/local-search.js"></script>






  





</body>
</html>
